public without sharing class SalesOrderApplicationHandler {
    
/*
	2、当海外销售订单审批状态变更为已批准时，将改本单执行总价(美元)累计汇总到关联的返利单的已用返利金额(美元)中。
*/
    public static void backToReturnSlip(List<SalesOrderApplication__c >list_new ,Map<Id,SalesOrderApplication__c>oldmap ){

        Set<Id > sodset = new Set<Id>();

    	for(SalesOrderApplication__c soa : list_new){
    		SalesOrderApplication__c old = oldmap.get(soa.Id);
    		if((soa.Status__c == '已批准' && old.Status__c != '已批准') || (soa.Status__c == '作废' && old.Status__c != '作废')){
                 sodset.add(soa.Id );

    		}
    	}
        if(sodset.size() == 0) return;
         Map<Id,Decimal > reslipMap = new Map<Id,Decimal>();

         Set<Id> rList = new Set<Id>();
        for (OrderRebateForm__c ord  :[select Id,RebateAmount__c,RebatefForm__c,Order__c ,Order__r.Status__c  from OrderRebateForm__c where Order__c in:sodset ] ) {
            if(ord.RebatefForm__c != null )rList.add(ord.RebatefForm__c);
        }

    
        for (OrderRebateForm__c ord  :[select Id,RebateAmount__c,RebatefForm__c,Order__c ,Order__r.Status__c  from OrderRebateForm__c where RebatefForm__c in:rList and Order__r.Status__c = '已批准'  ]  ) {
            Decimal td = reslipMap.containsKey(ord.RebatefForm__c) ? reslipMap.get(ord.RebatefForm__c) : 0 ; 

             td += (ord.RebateAmount__c  == null ? 0 : ord.RebateAmount__c);
            reslipMap.put(ord.RebatefForm__c, td );

        }

        // for(SalesOrderApplication__c soa :[select Id , ReturnSlip__c, RebateDeduction__c 
        //     from SalesOrderApplication__c  where ReturnSlip__c in :sodset and Status__c = '已批准' ]){

        //     Decimal td = reslipMap.containsKey(soa.ReturnSlip__c) ? reslipMap.get(soa.ReturnSlip__c) : 0 ; 
        //     td += (soa.RebateDeduction__c  == null ? 0 : soa.RebateDeduction__c);

        //     reslipMap.put(soa.ReturnSlip__c, td );


        // }
    	
    	List<ReturnSlip__c> rsList = new List<ReturnSlip__c>();
    	for(Id rid : reslipMap.keySet()){

    		rsList.add(new ReturnSlip__c(id=rid , ReturnAmountUsed__c = reslipMap.get(rid)));
    	}
        ///如果 不存在已批准的  则把原来的置为 0 ; 
        for(Id rid : rList ){
            if(!reslipMap.containsKey(rid)){
                rsList.add(new ReturnSlip__c(id=rid , ReturnAmountUsed__c = 0 ));
            }
        }
    	if(rsList.size() > 0) update rsList;

    }
}